<template>
    <div class="json-map">
        <div class="region-name">
            <span class="is-click" @click="SelectCity">无锡市</span>
            <i></i>
            <span>{{title}}</span>
        </div>
        <div class="radar" :style="{'background-image':`url(${radarbg})`}">
            <div class="scan" :style="{'background-image':`url(${radarscan})`}"></div>
        </div>
        <ul class="area-number">
            <li v-for="(item,index) in CompanyList" :key="index" class="number-li">
                <div class="li-icon" :style="{'background-color':colors[index]}">
                    <!-- <div class="line" :style="{'border-bottom-color':colors[index]}"></div> -->
                </div>
                <div class="li-txt">{{item.name}}</div>
                <div class="li-number">
                    <countTo :startVal="0" :endVal="item.number" :duration="3000"/>
                </div>
            </li>
        </ul>
        <!-- 源头企业 -->
        <div class="area-footer footer-config">
            <div class="corn corn-top-left"></div>
            <div class="corn corn-top-right"></div>
            <div class="corn corn-bottom-left"></div>
            <div class="corn corn-bottom-right"></div>
            <div class="number">
                <countTo :startVal="0" :endVal="cityYuantouCompanyNum" :duration="5000" />
            </div>
            <div class="txt">源头企业总数</div>
        </div>
        <!-- 接入总数 -->
        <div class="area-footer footer-total">
            <div class="corn corn-top-left"></div>
            <div class="corn corn-top-right"></div>
            <div class="corn corn-bottom-left"></div>
            <div class="corn corn-bottom-right"></div>
            <div class="number">
                <countTo :startVal="0" :endVal="totalNumber" :duration="5000" />
            </div>
            <div class="txt">接入企业总数</div>
        </div>
       <!-- 当日运单 -->
        <!-- <div class="area-footer  area-footer-right right1">
            <div class="corn corn-top-left"></div>
            <div class="corn corn-top-right"></div>
            <div class="corn corn-bottom-left"></div>
            <div class="corn corn-bottom-right"></div>
            <div class="number">
                <countTo :startVal="0" :endVal="cityYuantouCompanyNum" :duration="5000" />
            </div>
            <div class="txt">当日运单</div>
        </div> -->
        <!-- 当日称重 -->
        <!-- <div class="area-footer  area-footer-right right2">
            <div class="corn corn-top-left"></div>
            <div class="corn corn-top-right"></div>
            <div class="corn corn-bottom-left"></div>
            <div class="corn corn-bottom-right"></div>
            <div class="number">
                <countTo :startVal="0" :endVal="cityYuantouCompanyNum" :duration="5000" />
            </div>
            <div class="txt">当日称重</div>
        </div> -->
         <!-- 周超载比率 -->
        <!-- <div class="area-footer  area-footer-right right3">
            <div class="corn corn-top-left"></div>
            <div class="corn corn-top-right"></div>
            <div class="corn corn-bottom-left"></div>
            <div class="corn corn-bottom-right"></div>
            <div class="number">
                <countTo :startVal="0" :endVal="cityYuantouCompanyNum" :duration="5000" />
            </div>
            <div class="txt">周超载比率</div>
        </div> -->
        <div class="area-footer area-footer1">
             <div class="corn corn-top-left"></div>
            <div class="corn corn-top-right"></div>
            <div class="corn corn-bottom-left"></div>
            <div class="corn corn-bottom-right"></div>
            <div class="box">
                 <div class="number">
                <countTo :startVal="0" :endVal="waybillNumForToday" :duration="5000" />
            </div>
            <div class="txt">当日运单</div>
            </div>
            <div class="box">
                 <div class="number">
                <countTo :startVal="0" :endVal="weightNumForToday" :duration="5000" />
               </div>
               <div class="txt">当日称重</div>
            </div>
            <div class="box">
                 <div class="number xiaoshu">
                   <countTo :startVal="0" :endVal="weekOverWeightPercentage" :duration="5000" /><i>{{'.'+smail+'‰'}}</i>
                </div>
                 <div class="txt">周超载比率</div>
            </div>
        </div>
        <div ref="bgChart" class="bg-chart" :style="top === 158 ? 'height:calc(100% - 158px);padding: 79px 0' : $store.state.currRouter.to === 'home' ? 'height:calc(100% - 100px);padding: 50px 0' : ''"></div>
        <div ref="borderChart" class="border-chart" :style="top === 158 ? 'height:calc(100% - 158px);padding: 79px 0' : $store.state.currRouter.to === 'home' ? 'height:calc(100% - 100px);padding: 50px 0' : ''"></div>
        <div ref="chart" class="chart-cont" :style="top === 158 ? 'height:calc(100% - 158px);padding: 79px 0' : $store.state.currRouter.to === 'home' ? 'height:calc(100% - 100px);padding: 50px 0' : ''"></div>
    </div>
</template>
<script type='text/javascript'>
/**
 * 中国地图组件
 * 事件 “change” 返回地区名称
 */
import echarts from '@/lib/echarts'
import countTo from 'vue-count-to'
import provinces from '@/lib/provinces'
import types from '@/store/constants/types'
import ns from '@/store/constants/ns'
import { mapState } from 'vuex'
import { getElementSize } from '@/lib/util'

import {GetAreaCompanyListByProperty,GetConfigInformation,GetWayBillAndWeightInformationForDay} from '@/api/screenApi'
const nameSpaced = ns.MAP + '/'
const homeSpaced = ns.HOME + '/'
export default {
    name: 'JsonMap',
    props: {
        areaCode:{
            type: String,
            default:""
        },
        data: {type: Array, default: () => {return []}},
        
        top: {type: Number, default: 0},
    },
    components: { countTo },
    data() {
        return {
            InterVal:null,
            radarbg:require('@/assets/images/radar_bg.png'),
            radarscan:require('@/assets/images/radar_scan.png'),
            title:"重点源头企业分布情况",
            chart: null, //echart图表对象
            bgChart: null, //地图背景
            borderChart: null, //地图边框
            cityName: '', //当前选择的市，地图上名称
            countyName: '', //当前选择的县，地图上名称
            panelTitle: '',
            size: null, //地图容器大小
            CompanyList:[],
            totalNumber:0,
            cityYuantouCompanyNum:0,
            colors:['#4bd8b5', '#ff8080', '#ffd342', '#1981c9', '#0463de', '#70e7ef',"#67E0E3", "#9FE6B8", "#ff9f7f", "#fb7293", "#E062AE", "#E690D1", "#e7bcf3", "#9d96f5", "#8378EA", "#96BFFF"],
            waybillNumForToday:0,
            weekOverWeightPercentage:0,
            weightNumForToday:0,
            smail:0,
        }
    },
    computed: {
        ...mapState ( nameSpaced , {
            region: state => state.region,
        })
    },
    watch: {
        '$store.state.windowResizeState' () { //监听浏览器窗口变化
            this.reDraw()
        },
        'top' () {
            this.reDraw()
        },
        'region' () {
            if(echarts.getMap(this.region)) {
                this.renderMap(this.region)
            }
        },
        'data' () {
            if(this.chart) {
                this.chart.clear()
                this.bgChart.clear()
                this.renderMap(this.region)
            }
        },
        'areaCode' (){
            this.totalNumber = 0
            this.CompanyList = []
            this.GetAreaCompany()
            this.GetConfigCompany()
            this.GetInformationForDay()
        }
    },
    
    mounted() {
        this.init()
        Promise.all([this.GetAreaCompany(),this.GetConfigCompany(),this.GetInformationForDay()])
    },
    
    methods: {
        init () {
            const that = this
            that.size = getElementSize(that.$refs.chart, 'json-map')
            
            if(that.top) {
                that.size.height -= that.top
            }
            that.bgChart = echarts.init( that.$refs.bgChart, false, that.size )
            that.borderChart = echarts.init( that.$refs.borderChart, false, that.size )
            that.chart = echarts.init( that.$refs.chart, false, that.size )
            that.changeRegion('无锡市')
            that.chart.on('click',(params)=>{
                if(params.name && params.name!=='无锡市' && !params.data){
                    this.title = params.name+"企业分布情况"
                    let name = params.name;
                    let areaCode = ""
                    that.data.forEach(el=>{
                        if(el.indexOf(name)>-1){
                            areaCode = el[4]
                        }
                    })
                    
                    let obj = {
                        timer:true,
                        areaCode:areaCode,
                        stationId:""
                    }
                    this.changeRegion(name,obj)
                }else if(params.name&&params.name != '无锡市' && params.data && typeof(params.data) == 'object'){
                    let obj = {
                        timer:true,
                        name:params.data.name,
                        areaCode:params.data.areaCode,
                        stationId:params.data.stationId
                    }
                    this.$emit("SelectCompany",obj)
                }
                
                
            })
        },
        //获取源头企业
        async GetConfigCompany() {
            try {
                 let params={}
                if(this.areaCode==''){
                   params = {
                    areaCode: null
                   }
                }else{
                  params = {
                    areaCode: this.areaCode
                   }
                   }
                const res = await GetConfigInformation(params)
                
                this.cityYuantouCompanyNum = Number(res.cityYuantouCompanyNum)
            } catch (error) {
                // eslint-disable-next-line no-console
                console.log(error)
            }
        },
        //获取企业总数
        async GetAreaCompany(){
            try {
                
                let params = {
                    areaCode: this.areaCode
                }
                this.CompanyList = await GetAreaCompanyListByProperty(params)
                this.CompanyList.forEach(el=>{
                    this.totalNumber += el.number
                })
            } catch (error) {
                // eslint-disable-next-line no-console
                console.log(error)
            }
        },
        //获取当日运单，当日称重，周超载比率
      async  GetInformationForDay(){
           try {
                
                let params = {
                    areaCode: this.areaCode
                }
                let informationForDay = await GetWayBillAndWeightInformationForDay(params)
                this.waybillNumForToday=Number(informationForDay.waybillNumForToday)
                this.weekOverWeightPercentage=Number(informationForDay.weekOverWeightPercentage*10)
                if(informationForDay.weekOverWeightPercentage==null){
                    this.weekOverWeightPercentage=0
                }
                this.weightNumForToday=Number(informationForDay.weightNumForToday)
                this.smail=this.getCaption(Number(informationForDay.weekOverWeightPercentage*10).toFixed(1))
                console.log(informationForDay,this.areaCode)
            } catch (error) {
                // eslint-disable-next-line no-console
                console.log(error)
            }
        },
        getCaption(obj){
        var index=obj.lastIndexOf("\.");
        obj=obj.substring(index+1,obj.length);
        return obj;
       },
        changeRegion (name,obj) {
            let value = "";
            switch(name){
                case "无锡市":
                    this.countyName = ''
                    this.cityName = '无锡市'
                    value = "wuxi";
                    break;
                case "宜兴市":
                    this.countyName = '宜兴市'
                    this.cityName = ''
                    value = "yixing";
                    break;
                case "惠山区":
                    this.countyName = '惠山区'
                    this.cityName = ''
                    value = "huishan";
                    break;
                case "滨湖区":
                    this.countyName = '滨湖区'
                    this.cityName = ''
                    value = "binhu";
                    break;
                case "锡山区":
                    this.countyName = '锡山区'
                    this.cityName = ''
                    value = "xishan";
                    break;
                case "新吴区":
                    this.countyName = '新吴区'
                    this.cityName = ''
                    value = "xinwu";
                    break;
                case "江阴市":
                    this.countyName = '江阴市'
                    this.cityName = ''
                    value = "jiangyin";
                    break;
                case "梁溪区":
                    this.countyName = '梁溪区'
                    this.cityName = ''
                    value = "liangxi";
                    break;

            }
           
            const that = this
            let amount = {name: name, value, api:value} //获取地图json所需的参数
            
            const postData = {name: name,type:obj?2:1, areaCode: obj?obj.areaCode:"", stationId:obj?obj.stationId:""}
            that.$store.commit( nameSpaced + types.MAP_SET_POST_DATA, postData )
            that.$emit('change', postData)
            //选中状态
            const option = {
                geo: {
                    regions: [{
                        name: name,
                        itemStyle: {
                            areaColor: '#279bdc',
                            borderColor: '#fff'
                        }
                    }]
                },
            }
            that.chart.setOption(option)
            
            if(echarts.getMap(name)) { //是否已注册该地图
                if(name != that.region) {
                    that.$store.commit( nameSpaced + types.MAP_SET_REGION_NAME, name )
                }
            }else {
                that.$store.dispatch(nameSpaced + types.MAP_GET_JSON_FILE, amount)
            }
            

        },
        renderMap (map) {
            
            const that = this
            if(!map) { return }
            const options = {
                animation: false,
                
                tooltip: {
                    trigger: 'item',
                    formatter: function(data) {
                        //name , value, percent, seriesName
                        let str = '<div style="background-color:#32C5E9;border-radius: 4px;"><div style="padding:5px 10px;">' + data.name?data.name:"数量:"+data.data[3] + '</div></div>'
                        //console.log(data)
                        return str
                    },
                    backgroundColor: 'rgba(0, 168, 255, 0)',
                    textStyle: {
                        fontSize: 14
                    },
                    position: 'top',
                    confine: true,
                },
                geo: {
                    map: map,
                    layoutCenter: ['50%','50%'],
                    label: {
                        show: true,
                        color: '#fff',
                    },
                    itemStyle: {
                            areaColor: '#0b4587',
                            borderColor: '#03bbe2',
                            borderWidth: 2,
                    },
                    emphasis: {
                        label: {
                            show: true,
                            color: '#fff',
                        },
                        itemStyle: {
                            areaColor: '#279bdc',
                            borderColor: '#ffffff',
                            borderWidth: 2,
                            shadowColor: 'rgba(12, 138, 188, 1)',
                            shadowBlur: 2
                        },
                    },
                    regions: that.cityName ? [{
                        name: that.cityName,
                        itemStyle: {
                            areaColor: '#279bdc',
                            borderColor: '#fff'
                        }
                    }] : []
                },
                series: that.data.length > 0 ? that.getSeries(map) : []
            }
            const bgOptions = {
                animation: false,
                geo: {
                    map: map,
                    layoutCenter: ['50%','50%'],
                    label: {
                        emphasis: {
                            show: false
                        }
                    },
                    itemStyle: {
                        areaColor: '#2d607b',
                        borderWidth: 0,
                        //borderColor: '#00f0fb',
                        //shadowColor: '#1773c3',
                        //shadowBlur: 15
                    }
                },
            }
            const borderOption = {
                animation: false,
                geo: {
                    map: map,
                    layoutCenter: ['50%','50%'],
                    label: {
                        emphasis: {
                            show: false
                        }
                    },
                    itemStyle: {
                        areaColor: '#0b4587',
                        borderColor: '#03bbe2',
                        borderWidth: 2,
                        shadowColor: '#03bbe2',
                        shadowBlur: 5
                    }
                },
            }
            that.bgChart.setOption(bgOptions)
            that.borderChart.setOption(borderOption)
            that.chart.setOption(options)
        },
        getSeries (map) {
            if(map=='无锡市'){
                let series = [{
                    name: '分布',
                    type: 'effectScatter',
                    coordinateSystem: 'geo',
                    data: this.data,
                    symbolSize: 15,
                    showEffectOn: 'render',
                    rippleEffect: {
                        brushType: 'stroke'
                    },
                    hoverAnimation: true,
                    label: {
                        formatter (data) {
                            
                            return data.value[3]
                        },
                        position: 'right',
                        show: false
                    },
                    itemStyle: {
                        normal: {
                            color: '#6cebfc',
                            shadowBlur: 10,
                            shadowColor: '#333'
                        }
                    },
                },{
                    name: '数量',
                    type: 'scatter',
                    coordinateSystem: 'geo',
                    data:this.data,
                    symbol: 'pin',
                    symbolSize (value) {
                        
                        let size = 10
                        if(value){
                            let n = value[2]
                            if(n > 100000) {
                                size = 80
                            }else if(n > 10000) {
                                size = 70
                            }else if(n > 1000) {
                                size = 60
                            }else if(n > 100) {
                                size = 50
                            }else if(n > 10) {
                                size = 40
                            }else {
                                size = 30
                            }
                        }
                       
                        return size
                    },
                    hoverAnimation: false,
                    label: { 
                        formatter (data) {
                            return data.value[2]
                        },
                        align: 'center',
                        color: '#fff',
                        show: true
                    },
                    itemStyle: { 
                        color: '#ff5300',
                    },
                    emphasis: {
                        itemStyle: { 
                            color: '#6cebfc'
                        },
                    },
                    zlevel: 1
                }]
                return series
            }else{
                
                // let stationData = this.data.filter(el=>el.stationType==1).map(rs=>{
                //     return {
                //         stationId:rs.stationId,
                //         areaCode:rs.areaCode,
                //         name:rs.stationName,
                //         value:[Number(rs.longitude),Number(rs.latitude)]
                //     }
                // })
                // let concreteData = this.data.filter(el=>el.stationType==2).map(rs=>{
                //     return {
                //         stationId:rs.stationId,
                //         areaCode:rs.areaCode,
                //         name:rs.stationName,
                //         value:[Number(rs.longitude),Number(rs.latitude)]
                //     }
                // })
                // let wharfData = this.data.filter(el=>el.stationType==3).map(rs=>{
                //     return {
                //         stationId:rs.stationId,
                //         areaCode:rs.areaCode,
                //         name:rs.stationName,
                //         value:[Number(rs.longitude),Number(rs.latitude)]
                //     }
                // })
                let mapdata = this.data.map(rs=>{
                    return {
                        stationId:rs.stationId,
                        areaCode:rs.areaCode,
                        name:rs.stationName,
                        value:[Number(rs.longitude),Number(rs.latitude)]
                    }
                })
                
                let series = [{
                    name: '',
                    type: 'effectScatter',
                    coordinateSystem: 'geo',
                    data:mapdata,
                    symbolSize: 10,
                    hoverAnimation: true,
                    
                    itemStyle: { 
                        color: '#ff5300',
                    },
                    emphasis: {
                        itemStyle: { 
                            color: '#6cebfc'
                        },
                    },
                    zlevel: 1
                }
                // {
                //     name: '混凝土企业',
                //     type: 'effectScatter',
                //     coordinateSystem: 'geo',
                //     data:concreteData,
                //     symbolSize: 10,
                //     hoverAnimation: false,
                    
                //     itemStyle: { 
                //         color: '#FFB800',
                //     },
                //     emphasis: {
                //         itemStyle: { 
                //             color: '#FFB800'
                //         },
                //     },
                //     zlevel: 1
                // },
                // {
                //     name: '港口码头',
                //     type: 'effectScatter',
                //     coordinateSystem: 'geo',
                //     data:wharfData,
                //     symbolSize: 10,
                //     hoverAnimation: false,
                    
                //     itemStyle: { 
                //         color: '#009688',
                //     },
                //     emphasis: {
                //         itemStyle: { 
                //             color: '#009688'
                //         },
                //     },
                //     zlevel: 1
                // }
                ]
                return series
            }
            
        },
        reDraw () { //重绘图表
            const that = this
            if(that.chart && provinces[that.region]) {
                that.size = getElementSize(that.$refs.chart, 'json-map')
                if(that.top) {
                    that.size.height -= that.top
                }

                const size = provinces[that.region].size? that.size.width - provinces[that.region].space : that.size.height - provinces[that.region].space
                const options = {
                    geo: {
                        layoutSize: size,
                    },
                }
                that.bgChart.setOption(options)
                that.borderChart.setOption(options)
                that.chart.setOption(options)
                that.chart.resize(that.size)
                that.borderChart.resize(that.size)
                that.bgChart.resize(that.size)
            }else {
                that.init()
            }
        },
        //选择城市
        SelectCity(){
            const postData = {name: "无锡市", areaCode: '', stationId: "",type:1}
            this.title = "重点源头企业分布情况"
            this.$store.dispatch(homeSpaced + types.HOME_GET_DATA, postData)
            this.changeRegion('无锡市')
        },
        
    },
    beforeDestroy () {
        const that = this
        if(that.chart){
            that.chart.dispose()
            that.bgChart.dispose()
            that.borderChart.dispose()
        }
    },
}
</script>
<style lang='scss' scoped>
@import '../style/views/json-map.scss';
.radar {
        position: absolute;
        bottom: 192px;
        right: 10px;
        width: 150px;
        height: 150px;
        background-position: center;
        background-repeat: no-repeat;
        background-size: 80% auto;
        .legend {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            text-align: center;
            >span {
                position: absolute;
                top: 30%;
                left: 0;
                width: 100%;
                font-size: 12px;
            }
            >div {
                width: 10px;
                height: 10px;
                box-shadow: 0 0 6px 2px rgba(41, 181, 216, 0.2);
                border-radius: 100%;
                background-color: #1981c9;
                margin: 25% auto;
            }
            &:nth-child(1) {
                >div {
                    background-color: #4bd8b5;
                }
            }
            &:nth-child(2) {
                >div {
                    background-color: #ff8080;
                }
            }
            &:nth-child(3) {
                >div {
                    background-color: #ffd342;
                }
            }
        }
        .scan {
            height: 100%;
            background-position: center;
            background-repeat: no-repeat;
            background-size: 74% auto;
            animation: circle 8s infinite linear;
        }
    }
    .area-number{
        position: absolute;
        right: 20px;
        top: 0;
        list-style: none;
        .number-li{
            width:auto;
            display: flex;
            justify-content:flex-end;
            align-items: center;
            color: #6a9ffa;;
            .li-icon{
                width:25px;
                height: 15px;
                border-radius: 2px;
                
                margin-right:10px;
                .line{
                    display: block;
                    position: absolute;
                    top:50%;
                    transform: translateY(-50%);
                    left: -15px;
                    width:40px;
                    border-bottom:2px dashed;
                    z-index:0;
                }
            }
            .li-txt{
                width:100px;
                font-size:32rpx;
                margin-right:10px;
                text-align:right;
                color: #fff;
            }
            .li-number{
                width:20px;
                text-align:right;
                color:#f0ca61;
            }
        }
    }
    .area-footer{
        position: absolute;    
        left: 20px;
        font-size:18px;
        color:#fff;
        border-radius:4px;
        padding:15px;
        box-sizing: border-box;
        &.footer-config{
            bottom:220px;
        }
        &.footer-total{
            bottom: 350px;
        }
        .corn{
            position: absolute;
            width:10px;
            height: 10px;
            
            &.corn-top-left{
                top: 0;
                left: 0;
                border-top-left-radius:4px;
                border-top:2px solid #53a4f0;
                border-left:2px solid #53a4f0;
            }
            &.corn-top-right{
                top: 0;
                right: 0;
                border-top-right-radius:4px;
                border-top:2px solid #53a4f0;
                border-right:2px solid #53a4f0;
            }
            &.corn-bottom-left{
                bottom: 0;
                left: 0;
                border-bottom-left-radius:4px;
                border-bottom:2px solid #53a4f0;
                border-left:2px solid #53a4f0;
            }
            &.corn-bottom-right{
                bottom: 0;
                right: 0;
                border-bottom-right-radius: 4px;;
                border-bottom:2px solid #53a4f0;
                border-right:2px solid #53a4f0;
            }
            
        }
        .number{
            font-size: 32px;
            color: #fff;
            text-align:center;
            i{
               
               font-style: normal;
              
            }
        }
        .xiaoshu{
            display:flex;
            align-items: flex-end;
             justify-content: center;
        }
        .txt{
            font-size: 12px;
            color:#f0ca61;
            text-align:center;
        }
    }
    .area-footer1{
        display:flex;
        top:70px;
        padding:15px;
        z-index:3;
        .box{
            padding:0 15px;
        }
    }
    .area-footer-right{
         position:absolute;  
         top:70px;
         padding:15px;
        &.right3{
            
            //  bottom:220px;
             left:20px;
        }
        &.right2{
        //    bottom: 350px;
        left:150px;
        }
         &.right1{
            // bottom: 480px;
            left:280px;
        }
    }
    @keyframes circle {
        0% {
            transform: rotate(0deg);  
        }
        100% {
            transform: rotate(360deg);  
        }
    }
</style>